package com.huxianyang.config;

import com.huxianyang.converter.String2UserConverter;
import org.springframework.beans.BeansException;
import org.springframework.core.convert.converter.Converter;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

/**
 * 
 * @since 2022/06/01 21:27
 * @author HuXianyang
 */

// @Configuration
public class Converter3Configuration implements WebMvcConfigurer, ApplicationContextAware {
    ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void addFormatters(FormatterRegistry registry) {
        Map<String, Converter> converterMap = applicationContext.getBeansOfType(Converter.class);
        Collection<Converter> converters = converterMap.values();
        Iterator<Converter> converterIterator = converters.iterator();
        while (converterIterator.hasNext()) {
            Converter next = converterIterator.next();
            registry.addConverter(next);
        }
        registry.addConverter(new String2UserConverter());
    }
}